package com.mocha.filter;

import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.web.filter.AbstractRequestLoggingFilter;
import org.springframework.web.util.ContentCachingResponseWrapper;
import org.springframework.web.util.WebUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;

/**
 * 没有注册，示例代码，扩展日志打印，添加打印response信息
 */
public class RequestResponseLogFilter extends AbstractRequestLoggingFilter {
    private final String response_prefix = "reponse [";
    private final String response_suffix = "]";
    private final String request_prefix = "request [";
    private final String request_suffix = "]";


    @Override
    protected void beforeRequest(HttpServletRequest request, String message) {

    }

    @Override
    protected void afterRequest(HttpServletRequest request, String message) {

    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        HttpServletResponse responseToUse = response;

        filterChain.doFilter(request, response);

        String message = createMessage(request, request_prefix, request_suffix);

        ContentCachingResponseWrapper responseWrapper =
                WebUtils.getNativeResponse(responseToUse, ContentCachingResponseWrapper.class);
        message += getResponseMessage(responseWrapper);
        logger.info(message);

    }


    private String getResponseMessage(ContentCachingResponseWrapper responseWrapper) throws IOException {



        final StringBuilder responseMessage=new StringBuilder();
        responseMessage.append(response_prefix);
        responseMessage.append("status:");
        int status = responseWrapper.getStatus();
        responseMessage.append(status);
        responseMessage.append(";");

        if(isIncludeHeaders()){
            Collection<String> headerNames = responseWrapper.getHeaderNames();
            responseMessage.append("head:");
            headerNames.forEach(name->{
                responseMessage.append(name);
                responseMessage.append("=");
                responseMessage.append(responseWrapper.getHeader(name));
            });
            responseMessage.append(";");
        }

        String contentType = responseWrapper.getContentType();
        String applicationJsonValue = MediaType.APPLICATION_JSON_VALUE;
        if(contentType.contains(applicationJsonValue))
        {
//            body 只取 json
            try( InputStream contentInputStream = responseWrapper.getContentInputStream()) {
                String body = IOUtils.toString(contentInputStream, "utf-8");
                responseMessage.append("body:");
                responseMessage.append(body);
            } catch (IOException e) {
                logger.error("全局日志，body 内容提取",e);
            }
        }
        responseMessage.append(response_suffix);
        return responseMessage.toString();
    }
}
